package controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import common.PageReturn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import pojo.EssayAndUser;
import pojo.Page;
import pojo.User;
import service.EssayServiceI;
import service.UserServiceI;

@Controller
@RequestMapping("common")
public class CommonController {

	@Autowired
	private EssayServiceI essayServiceI;
	@Autowired
	private  UserServiceI userServiceI;
	@RequestMapping("search")
	    /**
	    　　* @param [request, modelAndView, session]
	    　　* @return org.springframework.web.servlet.ModelAndView
	    　　* @author：千夜
	    　　* @date 2019/4/21 10:15
	     　 * @description: 搜索文章（根据标题）以及用户
	    　　*/
	public ModelAndView search(HttpServletRequest request,ModelAndView modelAndView,HttpSession session) {
		String text=request.getParameter("searchtext");
		User user=(User) session.getAttribute("user");
		/**************************分页获取相关参数************************************/
		String Page=request.getParameter("currentPage");
		Integer currentPage;
		if(Page!=null){
			currentPage=Integer.valueOf(Page).intValue();
		}else{
			currentPage=1;
		}
		pojo.Page page=new Page();
		page.setLimitNumber(10);
		page.setCurrentPage(currentPage);
		PageReturn pageReturn=new PageReturn();
		page=pageReturn.ReturnPage(page);//填充page实体
		Integer locationPage=currentPage;
		modelAndView.addObject("currentPage",locationPage);
		/*************************************************************************/
		if(user==null) {
			List<User> users=userServiceI.FindUserByUserName(text,page);
			int usersCount=userServiceI.FindUserByUserNameCount(text);
			List<EssayAndUser> resultList=essayServiceI.SearchResultLogout(text,page);
			int resultListCount=essayServiceI.SearchResultLogoutCount(text);
			modelAndView.addObject("users", users);
/*			modelAndView.addObject("usersCount",usersCount);*/
			modelAndView.addObject("resultList", resultList);
			modelAndView.addObject("resultListCount",resultListCount);
			modelAndView.setViewName("/community/jsp/essay/searchresult");
		}else {
			List<User> users=userServiceI.FindUserByUserName(text,page);
			int usersCount=userServiceI.FindUserByUserNameCount(text);
			List<EssayAndUser> resultList=essayServiceI.SearchResultLogin(text,page);
			int resultListCount=essayServiceI.SearchResultLogoutCount(text);
			modelAndView.addObject("users", users);
/*			modelAndView.addObject("usersCount",usersCount);*/
			modelAndView.addObject("resultList", resultList);
			modelAndView.addObject("resultListCount",resultListCount);
			modelAndView.setViewName("/community/jsp/essay/searchresult");
		}
		return modelAndView;
	}

}
